package com.homedo.microservice.distributed.id.service.service;

import com.homedo.common.util.Detect;
import com.homedo.microservice.distributed.id.service.conf.GenerateNoConf;
import com.homedo.microservice.distributed.id.service.exception.InitException;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.sankuai.inf.leaf.IDGen;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.ZeroIDGen;
import com.sankuai.inf.leaf.snowflake.SnowflakeIDGenImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SnowflakeService implements InitializingBean, DisposableBean {

    private Logger logger = LoggerFactory.getLogger(SnowflakeService.class);
    private IDGen idGen;

    private static final DynamicStringProperty appId = DynamicPropertyFactory.getInstance().getStringProperty("application.id", "10246");

    @Autowired
    private GenerateNoConf generateNoConf;


    @Override
    public void afterPropertiesSet() throws Exception {
        boolean flag = generateNoConf.isEnable();
        if (flag) {
            String zkAddress = generateNoConf.getZkAddress();
            int port = generateNoConf.getZkPort();

            String connectionString = "";
            if (zkAddress.indexOf(",") > -1) {
                String[] zkAddressParts = zkAddress.split(",");
                for (String zkAddressPart : zkAddressParts) {
                    zkAddressPart = zkAddressPart.trim();
                    if (Detect.notEmpty(zkAddressPart)) {
                        connectionString += zkAddressPart + ":" + port + ",";
                    }
                }
                connectionString = connectionString.substring(0, connectionString.length() - 1);
            } else {
                connectionString = zkAddress + ":" + port;
            }

            String prefixZkPath = "/data/appdatas/" + appId.get() + "/zk";

            idGen = new SnowflakeIDGenImpl(connectionString, port, prefixZkPath);
            if (idGen.init()) {
                logger.info("Snowflake Service Init Successfully");
            } else {
                throw new InitException("Snowflake Service Init Fail");
            }
        } else {
            idGen = new ZeroIDGen();
            logger.info("Zero ID Gen Service Init Successfully");
        }
    }

    @Override
    public void destroy() throws Exception {

    }

    public Result getId(String key) {
        return idGen.get(key);
    }
}
